package cn.zealon.readingcloud.collection.service.impl;

import cn.zealon.readingcloud.collection.pojo.SearchBookItem;
import cn.zealon.readingcloud.collection.service.ESOperateService;
import cn.zealon.readingcloud.common.pojo.book.Book;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Index;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ESOperateServiceImpl implements ESOperateService {


    private static final Logger log = LoggerFactory.getLogger(ESOperateServiceImpl.class);

    /**
     * ES Jest 客户端对象
     */
    //要通过配置类手动注入，现在已经不支持自动注入了
    @Autowired
    private JestClient jestClient;

    /**
     * 索引别名
     */
    @Value("${es.aliasName}")
    private String aliasName;

    /**
     * 类型
     */
    @Value("${es.indexType}")
    private String indexType;

    @Override
    public void inputBookToES(Book book) {

        Index index = getSaveResult(book);
        JestResult result;
        try {
            result = jestClient.execute(index);
            boolean succeeded = result.isSucceeded();
            if (succeeded){
                log.debug(book.getBookName()+"存入ES失败!");
            }else {
                log.debug(book.getBookName()+"存入ES成功!");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private Index getSaveResult(Book book) {
        SearchBookItem searchBookItem = buildSaveBook(book);
        Index index = new Index.Builder(searchBookItem).index(aliasName).type(indexType).build();

        return index;
    }

    private SearchBookItem buildSaveBook(Book book) {
        SearchBookItem searchBookItem = new SearchBookItem();

        searchBookItem.setBookId(book.getBookId());
        searchBookItem.setBookName(book.getBookName());
        searchBookItem.setAuthor(book.getAuthorName());
        String categoryName = "全部";
//        频道id:0全部,1男生,2女生,3出版物
        switch (book.getDicCategory()) {
            case 0:
                categoryName = "全部";
            case 1:
                categoryName = "男生";
            case 2:
                categoryName = "女生";
            case 3:
                categoryName = "出版物";
            default:
                categoryName = "全部";
        }
        searchBookItem.setCategoryName(categoryName);
        searchBookItem.setDicCategory(book.getDicCategory());
        searchBookItem.setImgUrl(book.getImgUrl());
        searchBookItem.setBookScore(book.getBookScore());
        searchBookItem.setIntroduction(book.getIntroduction());

        return searchBookItem;
    }


}
